/*
 * 信息框类
 * @Author: ljb
 * @Date: 2018-09-13 11:48:15
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-09-28 14:10:39
 */

const PRIMARY_COLOR = '#ffffff';
const TITLE_COLOR = '#FFF';

export default class Tips {
	/**
	 * @param {image} image 背景图片对象
	 * @param {number} x 起点坐标 x
	 * @param {number} y 起点坐标 y
	 * @param {number} width 宽度
	 * @param {number} height 高度
	 * @param {string} title 高度
	 * @param {array} text 多行
	 */
	constructor(image, x, y, width = 266, height = 140, title = '', contents) {
		this.image = image;
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.title = title;
		this.contents = contents;
	}

	createTip() {
		const tips = document.createElement('canvas');
		tips.width = this.width;
		tips.height = this.height;
		const context = tips.getContext('2d');
		context.save();
		context.fillStyle = TITLE_COLOR;
		context.drawImage(this.image, 0, 0, this.width, this.height);
		context.fontWeight = 'bolder';
		context.font = '16px sans-serif';
		context.fillText(this.title, 18, 28);
		context.font = '16px sans-serif';
		context.fillStyle = PRIMARY_COLOR;
		const line_height = 24;
		let top = 34;

		// 可能没有key数组
		if (Array.isArray(this.contents)) {
			this.contents.forEach((item) => {
				if (item) {
					context.fillText(item, 18, top += line_height);
				}
			});
		} else {
			const contents = Object.keys(this.contents);
			contents.forEach((key) => {
				if (this.contents[key].name) {
					let text = this.contents[key].name;
					if (this.contents[key].problem) {
						text = `${text}：${this.contents[key].problem}`;
					}
					context.fillText(text, 18, top += line_height);
				}
			});
		}
		context.restore();
		return tips;
	}

	draw(context) {
		if (!this.contents) return;
		if (Array.isArray(this.contents) && this.contents.join('') === '') return;
		const tips = this.createTip();
		// context.clearRect(this.x, this.y, this.width, this.height);
		context.drawImage(tips, this.x, this.y, this.width, this.height);
	}

	/**
	 * 设置 title 和 text
	 * @param {string} title
	 * @param {array} text
	 */
	setContent(title, contents) {
		this.title = title;
		this.contents = contents;
	}

	/**
	 * 设置提示框的宽
	 * @param {*} width
	 */
	setWidth(width) {
		this.width = width;
	}

	/**
	 * 设置提示框的宽
	 * @param {*} height
	 */
	setHeight(height) {
		this.height = height;
	}
}

